package com.zhz.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 1、两数之和
 */
public class TwoSum1 {

    public static void main(String[] args) {
        TwoSum1 m = new TwoSum1();
        int[] nums = {2, 7, 11, 15};
        int target = 18;
        int[] result = m.twoSum1(nums, target);
        System.out.println("结果：" + Arrays.toString(result));

    }

    /**
     * 两数之和
     */
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }

    /**
     * 使用数组+map来解决
     */
    public int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }

}
